package cc.telecomdigital.tdstock.Services;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

import android.content.Context;

public class LS_GetServerTime
{	
	public class LS_GetServerTime_Result
	{
		public String	timeStamp;

		public LS_GetServerTime_Result(String iTimeString)
		{
			timeStamp = iTimeString;
		}
	}
	
	public interface ILS_GetServerTimeReport
	{
		void ILS_GetServerTime_Response(boolean iSuccessfulSend, LS_GetServerTime_Result iResult);
	}	
	
	private final int        trialMax = 2;	
	private final int		SOCKET_TIMEOUT		= 5000;
	private final int		CONNECT_TIMEOUT	= 5000;	
	private final int        waitNextTime        = 500;
	private final String LOG_TAG = "LS_GetServerTime";
	private final boolean debugMode = false;
	
	private Context ownerContext;
	private String  urlString;
	private String  urlPort;	
	private ILS_GetServerTimeReport reporter;
	
	
	public LS_GetServerTime(Context iOwner, String iURL, String iPort)
	{
		ownerContext = iOwner;
		urlString    = iURL;
		urlPort      = iPort;		
	}
	
	public synchronized void RequestData(ILS_GetServerTimeReport iTimeResponse)
	{
		reporter = iTimeResponse;
		// Start the Thread
		Thread internalThreadObj = new Thread()
		{
			//Send request thru a thread
			@Override
			public void run()
			{	
				//If no network, we could skip the next
				if (DeviceInfo.IsNetworkAvailable(ownerContext) == false)
				{
					if (reporter != null)
						reporter.ILS_GetServerTime_Response(false, new LS_GetServerTime_Result(""));
					return;
				}
				
				int 		  trialCount;
				HttpClient  client;
				HttpGet 	  request;
				HttpParams  modParams;
				LS_GetServerTime_Result result;
				
				client    = new DefaultHttpClient();
				request   = new HttpGet(urlString);
				modParams = request.getParams();

				// Change the setting
				HttpConnectionParams.setSoTimeout(modParams, SOCKET_TIMEOUT);
				HttpConnectionParams.setConnectionTimeout(modParams,CONNECT_TIMEOUT);				
				HttpConnectionParams.setSocketBufferSize(modParams, 8192);		
				request.setParams(modParams);				
				
				trialCount = 0;
				while(true)
				{										
					result = SendDataSub(client, request);
					//If we did not get the require login information
					if (result.timeStamp.equals(""))
					{
						++trialCount;
						if (trialCount < trialMax)
						{
							if (debugMode)
								TDStockLog.i(LOG_TAG, "SendRequest: Retry performed: " + trialCount);
							try
							{
								sleep(waitNextTime);
							}
							catch(Exception ex)
							{
								TDStockLog.e(LOG_TAG, "SendRequest: Ex=" + ex.toString());
							}							
							continue;
						}
					}
					
					if (reporter != null)
						reporter.ILS_GetServerTime_Response(true, result);				
					break;
				}
			}
		};
		internalThreadObj.setName(LOG_TAG);
		internalThreadObj.start();			
	}
		
	private LS_GetServerTime_Result SendDataSub(HttpClient iClient, HttpGet iRequest)
	{
		//prepare for the result			
		String timeParam;
		
		timeParam = "";
		//Now perform the sending and obtaining the expected data		
		try
		{
			HttpResponse webResponse;
			StringBuffer contentString;

			webResponse   = iClient.execute(iRequest);
			if ((webResponse == null) || (webResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK ))
				webResponse.getEntity().getContent().close();
			else
			{
				contentString = CommunicTools.GetWebResponseInStringBuffer(webResponse);
				timeParam = CommunicTools.FindXMLStringContent(contentString, "Time");
			}				
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();			
			TDStockLog.e(LOG_TAG, "SendDataSub=>ClientProtocolException: " + e.toString());
		}
		catch (IOException e)
		{
			e.printStackTrace();			
			TDStockLog.e(LOG_TAG, "SendDataSub=>IOException: " + e.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
			TDStockLog.e(LOG_TAG, "SendDataSub=>Exception: " + e.toString());
		}
		
		if (debugMode)
			TDStockLog.i(LOG_TAG, "SendDataSub: Report of data");
		
		return new LS_GetServerTime_Result(timeParam);
	}
}
